//
//  BannerScrollView.m
//  PullLeftToRefreshDemo
//
//  Created by zhou Can on 15/6/2.
//  Copyright (c) 2015年 zhou Can. All rights reserved.
//

#define kRefreshOffset 60

#import "BannerScrollView.h"

@interface BannerScrollView()

@property (strong, nonatomic) NSArray *items;
@property (strong, nonatomic) UILabel *nextPageLabel;
@property (assign, nonatomic) BOOL refreshFlag;

@end

@implementation BannerScrollView


- (instancetype)initWithFrame:(CGRect)frame withItems:(NSArray *)items
{
    self = [super initWithFrame:frame];
    if (self) {
        self.items = items;
        [self setup];
    }
    return self;
}

- (void)setup
{
    [self setDelegate:self];
    CGRect frame = CGRectZero;
    for (int i = 0; i < self.items.count; i++) {
        frame = CGRectMake(i*CGRectGetWidth(self.bounds), 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
        UIView *view = [[UIView alloc] initWithFrame:frame];
        [view setBackgroundColor:[UIColor colorWithRed:arc4random() % 255 / 255.0 green:arc4random() % 255 / 255.0 blue:arc4random() % 255 / 255.0 alpha:1]];
        [self addSubview:view];
    }
    [self setContentSize: CGSizeMake(CGRectGetWidth(self.bounds) * self.items.count, CGRectGetHeight(self.bounds))];
    self.nextPageLabel = [[UILabel alloc] init];
    [self.nextPageLabel setNumberOfLines:0];
    self.nextPageLabel.text = @"释放查看图文详情";
    CGRect bounds = [self.nextPageLabel.text boundingRectWithSize:CGSizeMake(20, CGFLOAT_MAX)
                                                     options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: self.nextPageLabel.font}
                                                     context:nil];
    [self.nextPageLabel setFrame:CGRectMake(CGRectGetMaxX(frame) + 20, CGRectGetMidY(frame) - bounds.size.height/2, 20, bounds.size.height)];
    [self addSubview:self.nextPageLabel];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat contentOffsetX = scrollView.contentOffset.x;
    if (contentOffsetX - (scrollView.contentSize.width - CGRectGetWidth(scrollView.bounds)) > kRefreshOffset) {
        if (!self.refreshFlag) {
            self.nextPageLabel.text = @"可以释放刷新了";
            self.refreshFlag = YES;
        }
        
    }
}



- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (self.refreshFlag) {
        if (self.needRefresh) {
            self.needRefresh();
            self.nextPageLabel.text = @"释放查看图文详情";
            self.refreshFlag = NO;
        }
    }
}

@end
